package cc.cc4414.cc02.system.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import cc.cc4414.cc02.system.entity.Authority;
import java.lang.String;

/**
 * @author cc 2018年6月12日
 */
public interface AuthorityRepository extends JpaRepository<Authority, Long> {
	Authority findByName(String name);

	/**
	 * 通过用户id查找该用户所拥有的所有权限
	 * 
	 * @param userId
	 *            用户id
	 * @return 该用户所拥有的所有权限
	 */
	@Query(value = "select distinct a.* from authority a, role_authority ra, user_role ur where ur.user_id = ? and ur.role_id = ra.role_id and ra.authority_id = a.id", nativeQuery = true)
	List<Authority> findByUserId(Long userId);

	/**
	 * 通过资源id查找能访问该资源的所有权限
	 * 
	 * @param resourceId
	 *            资源id
	 * @return 能访问该资源的所有权限
	 */
	@Query(value = "select a.* from authority a, resource_authority ra where ra.resource_id = ? and ra.authority_id = a.id", nativeQuery = true)
	List<Authority> findByResourceId(Long resourceId);

	/**
	 * 通过角色id查找该角色所拥有的所有权限
	 * 
	 * @param roleId
	 *            角色id
	 * @return 该角色所拥有的所有权限
	 */
	@Query(value = "select a.* from authority a, role_authority ra where ra.role_id = ? and ra.authority_id = a.id", nativeQuery = true)
	List<Authority> findByRoleId(Long roleId);

	/**
	 * 删除所有角色的authorityId权限
	 * 
	 * @param authorityId
	 *            权限id
	 */
	@Modifying
	@Query(value = "delete from role_authority where authority_id = ?", nativeQuery = true)
	void deleteRoleAuthorityByAuthorityId(Long authorityId);

	/**
	 * 将所有资源所需的authorityId权限删除
	 * 
	 * @param authorityId
	 *            权限id
	 */
	@Modifying
	@Query(value = "delete from resource_authority where authority_id = ?", nativeQuery = true)
	void deleteResourceAuthorityByAuthorityId(Long authorityId);
}
